package com.Babysleep.Activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.Babysleep.R;
import com.Babysleep.Interface.Count_Handler;
import com.Babysleep.manage.MaMaShuoPlay;
import com.Babysleep.manage.Record;
import com.Babysleep.manage.ShiTing;

public class MaMaShuo extends BasicActivity {
	private Record record;
	// private Handler mHandler;
	private long start_time = 0;
	// private long end_time = 0;
	private String file_name = null;
	private Count_Handler handler;
	private ShiTing templayer;
	private listener mylistener = new listener();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		SharedPreferences setting = getSharedPreferences("settings", 0);
		boolean has_record = setting.getBoolean("has_audio", false);
		if (has_record == false) {
			no_audio_init();
		} else {
			with_audio_init(setting.getString("song_name", null));
		}
	}

	/**
	 * 无录音页面初始化。
	 */
	public void no_audio_init() {
		setContentView(R.layout.without_record_page);
		findViewById(R.id.record).setOnClickListener(mylistener);
		record = new Record(this);
		handler = new Count_Handler(MaMaShuo.this);
		findViewById(R.id.back_to_list).setOnClickListener(mylistener);
		findViewById(R.id.record).setOnClickListener(mylistener);
	}

	/**
	 * 有录音初始化
	 */
	public void with_audio_init(String name) {
		setContentView(R.layout.has_record_page);
		findViewById(R.id.back_to_list).setOnClickListener(mylistener);
		findViewById(R.id.start).setOnClickListener(mylistener);
		findViewById(R.id.cycle).setOnClickListener(mylistener);
		findViewById(R.id.del).setOnClickListener(mylistener);
		findViewById(R.id.del_confirm).setOnClickListener(mylistener);
		player = new MaMaShuoPlay(this);
		player.init((ImageButton) findViewById(R.id.start),name);
		TextView view = (TextView) findViewById(R.id.name);
		SimpleDateFormat df = new SimpleDateFormat("mm:ss");
		df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
		view.setText(name + "            " + df.format(player.getDuration()));// 读取音频时长
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case 8:
			if (record != null && record.Is_Recording == true) {
				record.stop();
				no_audio_init();
				return true;
			}
			if (templayer != null) {
				if (templayer.isPlaying()) {
					templayer.Stop();
				}
				no_audio_init();
				return true;
			}
			break;

		default:
			break;
		}

		return super.onKeyDown(keyCode, event);
	}

	class listener implements OnClickListener {

		/*
		 * 监听本activity的单击事件
		 */
		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			// 返回list
			case R.id.back_to_list:
				back_to_list();
				break;
			// 开始与停止录音
			case R.id.record:
				start_record();
				break;
			case R.id.stop_record:
				stop_record();
				break;
			// 点击红叉清空输入的文字
			case R.id.delete_content:
				clear_content();
				break;
			// 试听
			case R.id.listen:
				listen();
				break;
			// 保存文件
			case R.id.save:
				save_file();
				break;
			// 取消保存文件
			case R.id.cancle:
				cancle();
				break;
			// 开始播放妈妈的录音
			case R.id.start:
				player.Play();
				break;
			// 设置循环模式
			case R.id.cycle:
				set_cycle();
				break;
			// 删除当前录音
			case R.id.del:
				findViewById(R.id.del_confirm).setVisibility(View.VISIBLE);
				break;
			case R.id.del_confirm:
				del_file();
				break;
			default:
				break;
			}

		}

	}

	public void del_file() {
		SharedPreferences setting = getSharedPreferences("settings", 0);
		new File(setting.getString("song_name", null)).delete();
		if (player.isPlaying()) {
			player.Stop();
		}
		SharedPreferences.Editor editor = setting.edit();
		editor.putBoolean("has_audio", false);
		editor.putString("song_name", null);
		editor.commit();
		no_audio_init();
	}

	public void listen() {
		((TextView) findViewById(R.id.fenge)).setVisibility(1);
		((TextView) findViewById(R.id.counter)).setText("00:00");
		templayer.Play();

	}

	/**
	 * 停止录音
	 */
	public void stop_record() {
		// 由于发送消息时，end_time多算出了一秒，得减去。
		// end_time = System.currentTimeMillis() - 1000;
		record.stop();
		// isNeedSend = false;
		file_page_init();
	}

	/**
	 * 开始录音，设置XML。
	 */
	public void start_record() {
		setContentView(R.layout.recording);
		findViewById(R.id.stop_record).setOnClickListener(mylistener);
		start_time = record.start();
		file_name = Environment.getExternalStorageDirectory() + "/mamashuo/"
				+ String.valueOf(start_time) + ".amr";
		try {
			handler.start();
		} catch (Exception e) {
			System.out.println(e.toString());
		}

	}

	/**
	 * 初始化保存文件页面
	 */
	void file_page_init() {
		setContentView(R.layout.save_file);
		TextView file_length = (TextView) findViewById(R.id.file_length);
		findViewById(R.id.delete_content).setOnClickListener(mylistener);
		findViewById(R.id.listen).setOnClickListener(mylistener);
		findViewById(R.id.save).setOnClickListener(mylistener);
		findViewById(R.id.cancle).setOnClickListener(mylistener);
		SimpleDateFormat df = new SimpleDateFormat("mm:ss");
		df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
		// file_length.setText(df.format(end_time - start_time));
		templayer = new ShiTing(MaMaShuo.this);
		templayer.init((ImageButton) findViewById(R.id.listen),file_name);
		file_length.setText(df.format(templayer.getDuration()));
	}

	/**
	 * 保存文件,mamashuo文件夹下只允许一个文件存在，如果出现同名文件，无提示，删之。
	 */
	public boolean save_file() {
		EditText view;
		SharedPreferences settings = getSharedPreferences("settings", 0);
		view = (EditText) findViewById(R.id.file_name);
		if (view.getText() == null) {
			return false;
		}
		file_name = Environment.getExternalStorageDirectory() + "/mamashuo/"
				+ view.getText().toString() + ".amr";
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/mamashuo/" + start_time + ".amr");
		File file2 = new File(file_name);
		if (file2.exists() && !settings.getBoolean("has_audio", false)) {
			// 有重名的，并且settings里记录没有录音文件，删之。
			file2.delete();
		}

		// 重命名文件，在settings里做记录。
		if (file.renameTo(new File(file_name))) {
			SharedPreferences.Editor editor = settings.edit();
			editor.putBoolean("has_audio", true);
			editor.putString("song_name", file_name);
			editor.commit();
			System.out.println(settings.getBoolean("has_audio", true));
			// listen = null;// 释放listen
			with_audio_init(file_name);
			return true;
		} else {
			return false;
		}

	}

	/**
	 * 取消 本录音
	 */
	public void cancle() {
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/mamashuo/" + start_time + ".amr");
		file.delete();
		// listen.stop(handler);
		no_audio_init();
	}

	/**
	 * 清空输入框内容
	 */
	public void clear_content() {
		EditText view = (EditText) findViewById(R.id.file_name);
		view.setText("");
	}
}